<template>
  <div class="attach-wraper">
    <template v-if="value.length">
      <div
        class="item"
        v-for="item in value"
        :key="item.content"
        @click="openAction(item)"
      >
        <div class="icon-container">
          <img :src="imgSrc(item)" class="thumbnail" />
          <div class="loadding">
            <van-loading type="spinner" class="spinner-container" />
          </div>
        </div>

        <div class="right-side">
          <p class="file-name text-overflow">{{ item.fileName }}</p>
          <span class="file-size">{{ getFileSize(item.fileSize) }}</span>
        </div>
      </div>
    </template>
    <div v-if="!isEmailDetail" class="add-item item" @click="openChannelAction">
      <div class="add-icon-wrapper">
        <img class="add-icon" :src="require('@/assets/oppo/add-item.svg')" />
      </div>
      <p>{{ $lang.addAttach }}</p>
      <input
        style="display: none"
        type="file"
        accept="application/pdf"
        ref="filesInput"
        name="iCloud"
        @change="handleFileHTML"
      />

      <!-- 不限制格式 开发时测试图片专用 需注释-->
      <!-- <input
        style="display: none"
        type="file"
        ref="filesInput"
        accept="image/*,video/*,audio/*,application/*,text/*"
        @change="handleFileHTML"
      /> -->
    </div>

    <van-action-sheet
      v-model="showAction"
      :actions="isEmailDetail ? emailDetailAction : actions"
      :cancel-text="$lang.cancel"
      close-on-click-action
      @select="onSelect"
    />
  </div>
</template>

<script>

import { getFileSize, fileToBinary, getFileExt, getUrlParam } from "@/utils/helper";
// import { ImagePreview } from "vant";
import { fileIcon } from "../config/fileExtIcon";
import { Dialog } from "vant";
import {getFontScale} from "@/utils/CommonUtil";
export default {
  props: {
    // 父组件双向绑定默认传递value值给子组件
    // 附件列表
    value: {
      type: Array,
      default: () => [],
    },
    // 分片比特大小， 默认按3m分片
    fragment: {
      type: Number || String,
      default: 3,
    },
    messageID: {
      type: String,
    },
    isEmailDetail: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    wholeAttachSize() {
      //附件总大小
      const wholeSize = this.value.reduce((accu, item) => {
        return accu + item.fileSize;
      }, 0); //单位B
      const sizeInMB = wholeSize / 1024 / 1024;
      return sizeInMB;
    },
  },
  data() {
    return {
      showAction: false,
      actions: [
        { name: this.$lang.preview, value: "preview", className: "lineClass" },
        { name: this.$lang.delete, value: "del", color: "red" },
      ],
      emailDetailAction: [{ name: this.$lang.preview, value: "preview" }],
      selectedImg: {},
    };
  },
  methods: {
    openChannelAction() {
      this.$emit("openChannelAction");
    },

    imgSrc(item) {
      const fileSuffix = getFileExt(item.fileName);
      // console.warn('fileSuffix==', fileSuffix)
      // let extIcon = "";
      // const imgFormats = ["png", "PNG", "jpeg", "jpg"];
      // if (!imgFormats.includes(fileSuffix)) {
      //   // console.warn('另外设置图标')
      //   extIcon = fileIcon(fileSuffix);
      // } else {
      // console.warn('本身图片内容')
      // return item.content || item.fileUrl;
      // }
      // return extIcon;
      return fileIcon(fileSuffix);
    },

    //--qing 云之家 JS桥-----------
    openPhotoChannel() {
      const _this = this;
      window.qing.call("selectPic", {
        type: "photo",
        success: function (result) {
          console.warn(result?.data);
          const { fileExt, fileData } = result?.data;
          const res = `data:image/${fileExt};base64,${fileData}`;
          //因js桥没有返回图片名字，截取时间戳作为文件名
          const picName = +new Date();
          _this.handleFile(res, `oppomail-${picName}.${fileExt}`);
        },
        error: function (result) {
          // this.$toast.fail('上传失败')
          console.error("错误打开结果", result);
        },
      });
    },
    //打开拍照
    openCameraChannel() {
      const _this = this;
      try{
        window.qing.call("selectPic", {
        type: "camera",
        success: function (result) {
          console.warn(result,"桥调用成功了");
          const { fileExt, fileData } = result?.data;
          const res = `data:image/${fileExt};base64,${fileData}`;
          const picName = +new Date();
          _this.handleFile(res, `oppomail-${picName}.${fileExt}`);
        },
        error: function (result) {
          console.error("错误打开结果", result);
        },
        });
      }catch(err){
        console.warn("selectpic调用失败",eerr);
      }

    },

    //打开附件(不限制格式)
    openFileChannel() {
      const { filesInput } = this.$refs;
      filesInput?.click();

      // const _this = this;
      // window.qing.call("selectFile", {
      //   success: function (result) {
      //     console.warn(result);
      //     // const { files } = result?.data

      //     // _this.handleFile(result.data.files);
      //   },
      //   error: function (result) {
      //     console.error("错误打开结果", result);
      //   },
      // });
    },

    // 处理原生input输入的文件
    handleFileHTML(file) {
      let that = this;
      const { filesInput } = this.$refs;
      const reader = new FileReader();
      // 转换成base64
      reader.readAsDataURL(file.target.files[0]);
      reader.onloadend = function () {
        that.value.push({
          content: reader.result,
          fileSize: file?.target?.files[0]?.size,
          fileName: file?.target?.files[0]?.name,
          fileType: file?.target?.files[0]?.type,
          file: file?.target?.files[0],
          fileUrl: "",
          id: "",
          status: "unfinish",
        });
        that.fileUploader(file?.target?.files[0]);
        filesInput.value = null;
      };
    },
    //处理云之家js桥上传的文件
    handleFile(base64, fileName) {
      const file = this.dataURLtoFile(base64, fileName);
      this.value.push({
        content: base64,
        fileSize: file?.size,
        fileName: file?.name,
        fileType: file?.type,
        file: file,
        fileUrl: "",
        id: "",
        status: "unfinish",
      });
      this.fileUploader(file);
    },
 
    dataURLtoFile(dataUrl, filename = "default-file-name") {
      var arr = dataUrl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 文件上传
    fileUploader(file) {
      // 1M 等于1024*1024字节
      const oneM = 1024 * 1024;
      if (!file) {
        console.error("未获取到文件");
      }
      if (this.wholeAttachSize > 33) {
        //邮件总大小限制在35M， 其中附件总大小应小于33M，剩余2M留给文本内容
        this.$toast.fail(this.$lang.wholeAttachSizeLimit);
        this.value.pop();
        return;
      }
      //附件单个大小应小于33M
      if (file?.size <= oneM * 33) {
        if (file?.size > oneM * this.fragment) {
          this.fragmentUpload(file);
        } else {
          this.normalUpload(file);
        }
      } else {
        this.$toast.fail(this.$lang.attachSizeLimit);
        this.value.pop();
        return;
      }
    },

    // 普通上传
    async normalUpload(file) {
      try {
        const formData = new FormData();
        let _this = this;
        formData.append("file", file);
        formData.append("messageId", _this.messageID);
        const res = await this.Api.uploadFile(formData);
        const { success } = res?.data;
        if (success) {
          const { data } = res?.data;
          const len = _this.value?.length;
          if (len) {
            _this.value[len - 1].status = "finished";
            _this.value[len - 1].id = data?.id || "";
          }
          console.warn("普通上传-data:图片信息", data);
        }
        this.$toast.clear()
      } catch(e){
        this.$toast.clear()
        console.error("普通上传图片失败",e);
      }
    },
    // 分片上传
    async fragmentUpload(file) {
      const oneM = 1024 * 1024;
      const requestBody = {
        messageId: this.messageID,
        name: file?.name,
        size: file?.size,
      };
      let _this = this;
      try {
        const res = await this.Api.bigFileUpload(requestBody);
        const { success } = res?.data;
        if (success) {
          const { data } = res?.data;
          const uploadUrl = data?.uploadUrl;
          const fileChunk = fileToBinary(file, this.fragment * oneM);
          console.warn("fileChunk");
          console.warn(fileChunk);
          // 此处用for，其他循环是异步的
          for (let i = 0; i < fileChunk?.length; i++) {
            const start = i === 0 ? 0 : i * this.fragment * oneM;
            const end = start + fileChunk[i].size - 1;
            const header = {
              contentRange: `bytes ${start}-${end}/${file.size - 1}`,
              contentLength: fileChunk[i].size,
            };
            console.warn("header");
            console.warn(header);
            try {
              const fRes = await this.Api.fragmentUpload(
                uploadUrl,
                fileChunk[i],
                header
              );

              // console.warn('fRes')
              // console.warn(fRes)

              // 最后一次分片，会把文件id放在location，用正则截取下
              if (fRes?.status === 201) {
                const location = fRes?.headers?.location;

                console.warn("location");
                console.warn(location);

                // const reg = /(?<=Attachments\(').+(?='\))/;
                // const reg = new RegExp(/(?<=Attachments\(').+(?='\))/);
                const reg = new RegExp(/Attachments\('(.+)'\)/);
                const matchResult = location.match(reg);
                const id = matchResult[1];

                console.error("id", id);
                // console.warn('matchResult[1]')
                // console.warn(matchResult[1])

                const len = _this.value?.length;
                if (len) {
                  _this.value[len - 1].status = "finished";
                  _this.value[len - 1].id = id || "";
                }
              }
          this.$toast.clear()
            } catch {
              _this.value.pop();
              _this.$toast.fail(this.$lang.uploadImageFail);
              console.error("分片上传失败");
            }
          }
        }
      } catch {
        _this.$toast.fail(this.$lang.uploadImageFail);
        console.error("大文件上传会话建立失败");
      }
    },

    getFileSize(fileSize) {
      return getFileSize(fileSize);
    },
    // 打开选择面板
    openAction(item) {
      this.showAction = true;
      this.selectedImg = item;
    },
    // onSelect(action) {
    //   let _this = this;
    //   if (action?.value === "preview") {
    //     ImagePreview({
    //       images: [_this.selectedImg.fileUrl || _this.selectedImg.content],
    //     });
    //   } else {
    //     const index = _this.value.findIndex(
    //       (f) => f.id === _this.selectedImg?.id
    //     );
    //     if (index > -1) {
    //       _this.value.splice(index, 1);
    //     }
    //   }
    // },

    //删除附件
    async delAttach(attachmentId) {
      try {
        const requestBody = {
          messageId: this.messageID,
          attachmentId: attachmentId,
        };
          this.Api.delAttachment(requestBody).then( res =>{
            const { success, data } = res?.data;
            if (success) {
              this.$toast.success(this.$lang.successDelete);
            }
          })
      } catch {
        console.error("删除附件失败");
      }
    },
    //  getPreviewUrl() {

    //     const res = this.Api.getPreviewUrl(
    //       this.messageID,
    //       this.selectedImg.id

    //     );
    //     // console.warn("文件预览返回数据:");
    //     // console.warn(res.data);

    //     console.warn("processTime", processTime);
    //     const { success, errorCode } = res.data;
    //     if (success) {
    //       // let url = res?.data?.data;
    //       // //打开文件预览界面
    //       // this.openPreview(url, {
    //       //   appName: _this.selectedImg.fileName || "附件",
    //       // });
    //       this.$toast.clear();
    //       return res
    //     } else {
    //       this.$toast.clear();
    //       this.$toast.fail(this.$lang.previewNotSupported);
    //     }

    // },
    //  DialogWhenPreviewSlow() {
    //   const startTime = +new Date();
    //   const res = this.Api.getPreviewUrl(
    //       this.messageID,
    //       this.selectedImg.id

    //   );
    //   res.then()
    //   const { success, error } = res?.data;
    //   if(success){
    //     const endTime = +new Date();
    //     const processTime = endTime - startTime;
    //     console.warn(`processTime: ${processTime}`)
    //     let url = res?.data?.data;
    //     this.openPreview(url, {
    //       appName:    this.selectedImg.fileName || "附件",
    //     });
    //   }
    //   // Dialog.confirm({
    //   //   title: this.$lang.openPreviewNoti,
    //   //   // message: this.$lang.openPreviewNoti,
    //   //   confirmButtonText: this.$lang.openPreviewContinueWaiting,
    //   //   cancelButtonText: this.$lang.openPreviewTryAgain,
    //   //   className: "errSelfDialog",
    //   // })
    //   //   .then(() => {

    //   //   })
    //   //   .catch(() => {

    //   //   });
    // // },
    async onSelect(action) {
      //async
      let _this = this;
      if (action?.value === "preview") {
        // console.warn("openwebview",":::action",_this.selectedImg.id);
        // console.warn("messageid:",this.messageID);
        // console.warn("value",this.value);
        // ImagePreview({
        //   images: [_this.selectedImg.fileUrl || _this.selectedImg.content],
        // });
        this.$toast.loading({
          message: this.$lang.loading,
          forbidClick: true,
          duration: 0,
        });
        if (!_this.selectedImg.id) {
          this.$toast.fail(this.$lang.fileUploadNotFinished);
          return;
        }
        // await this.DialogWhenPreviewSlow()
        try {
          // 获取文件预览的url
          const res = await this.Api.getPreviewUrl(
            this.messageID,
            _this.selectedImg.id
          );
          // 先取消await 让该操作请求变为异步
          // 考虑开启定时器前是否判断！（最好判断下！防止后面用户长时间未选择，）
          // 在此处开启定时器，5秒后，进行判断数据是否返回（res,是否存在数据），如果存在，取消 loading ，跳转页面，
          // 如果不存在，打开弹窗，点击弹窗取消，不进行跳转，return，点击弹窗继续等待，开启新的定时器，
          // console.warn("文件预览返回数据:",res.data.success,res);
          if(res.data?.success && res?.data?.success == true){
            const { success, errorCode } = res.data;
            if (success) {
              let url = res?.data?.data;    
              const watermark_txt = getUrlParam("watermark_txt",url)
              let a = "watermark_txt="+ watermark_txt;
              let encodeurl = encodeURI("watermark_txt="+watermark_txt)
              let url1 = url.replace(a,encodeurl)
              console.warn(url1);
              // 将水印转义后的url传入
              this.openPreview(url1, {
                appName: _this.selectedImg.fileName || "附件",
              });
              this.$toast.clear();
            } 
          }else {
              console.warn("附件返回的错误1",res);
              if(typeof res == 'number'&& res != 600  ){
                this.$toast.fail(this.$lang.errorServer)
              }else if (typeof res != 'number'){
                this.$toast.clear();
                this.$toast.fail(res.data.error);
              }
            }
        } catch (error) {
          console.warn(error,"throw返回的错误");
          this.$toast.clear();
          let res = error?.data?.data;
          res === null
            ? this.$toast.fail(this.$lang.previewNotSupported)
            : this.$toast.fail(this.$lang.previewError);
        }
      } else {
          Dialog.confirm({
          message: this.$lang.sureDel,
          confirmButtonText: this.$lang.yes,
          cancelButtonText:this.$lang.no
        })
        .then(() => {
          console.warn("删除附件");
          const index = _this.value.findIndex(
            (f) => f.id === _this.selectedImg?.id
          );
          if (index > -1) {
            _this.delAttach(_this.value[index].id).then(() =>{
              _this.value.splice(index, 1);
            })
          }
        })
        .catch(() => {
          return 
        });  
       
      }
    },
  },
};
</script>

<style lang="less" scoped>
.attach-wraper {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
  background: #fff;
  .item {
    height: 1.5466688rem;
    width: 100%;
    border-radius: 4px;
    padding: 11px 12px;
    background: #f7f8fa;
    margin-top: 8px;
    display: flex;
    flex-direction: row;
    align-items: center;
    z-index: 1;
    .icon-container {
      display: flex;
      height: 36px;
      width: 36px;
      overflow: hidden;
      .thumbnail {
        // height: 36px;
        // width: 36px;
        object-fit: cover;
        margin-right: 8px;
      }
      .loadding {
        width: 18px;
        display: flex;
        justify-content: center;
        align-items: center;
        .spinner-container {
          height: 36px;
          width: 36px;
        }
      }
    }

    .right-side {
      display: flex;
      flex-direction: column;
      .file-name {
        width: 270px;
        font-size: 14px;
        color: #323233;
      }
      .file-size {
        font-size: 12px;
        color: #969799;
      }
    }
  }
  .add-item {
    font-size: 14px;
    color: #323233;
    display: flex;
    align-items: center;
    // justify-content: center;
    .add-icon-wrapper {
      width: 36px;
      height: 36px;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      margin-right: 8px;
      .add-icon {
        pointer-events: none;
      }
    }
  }
}
.lineClass {
  font-size: 16px;
  color: #323233;
  text-align: center;
  line-height: 24px;
  font-weight: 400;
  position: relative;
}
.lineClass::after {
  content: "";
  position: absolute;
  bottom: 0;
  background: #ebedf0;
  width: calc(100% - 40px);
  left: 20px;
  right: 20px;
  height: 1px;
  opacity: 0.5;
}
</style>
